package com.cy.pj.goods.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DefaultGoodsDao implements GoodsDao{
   @Autowired
    private DataSource dataSource;

    @Override
    public List<Map<String, Object>> findGoods() {
        Connection conn=null;
        Statement stmt=null;
        ResultSet rs=null;
        String sql="select * from tb_goods";

        try {
            conn=dataSource.getConnection();
            stmt=conn.createStatement();
            rs=stmt.executeQuery(sql);

           List<Map<String,Object>> list= new ArrayList<>();
          //处理结果集
           while (rs.next()){//循环一次取一次，一行记录映射为一个map对象
               list.add(rowMap(rs));
           }
           return list;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            try {
                rs.close();
                stmt.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
    //定义行映射方法
    private Map<String,Object> rowMap(ResultSet rs)throws SQLException{
       Map<String,Object> rowMap=new HashMap<>();

        ResultSetMetaData rsmd=rs.getMetaData();
        int columnCount=rsmd.getColumnCount();

        for (int i=0;i<columnCount;i++){
            rowMap.put(rsmd.getColumnLabel(i+1),
                    rs.getObject(rsmd.getColumnLabel(i+1)));
        }
        return rowMap;
    }

    //定义释放资源
    private  void  close(ResultSet rs,Statement stmt,Connection conn){
        if(rs!=null)
            try{
                rs.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        if(stmt!=null)
            try{
                stmt.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        //这里的连接是返回到了池中
        if(conn!=null)
            try{
                conn.close();
            }catch(Exception e){
                e.printStackTrace();
            }
    }
}
